﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MS_Entity;
using STMS.DbUtility;

namespace MS_UI
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
        }

        private void btn_Login_Click(object sender, EventArgs e)
        {
            //判断是否匿名登录
            if (this.chk_UsePWD.Checked)
            {
                this.DialogResult = DialogResult.OK;
                CommonMethods.objAdmins.LoginName = "none";
            }
            else
            {
                if (this.txt_LoginName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请输入用户名！");
                    this.txt_LoginName.Focus();
                    return;
                }
                if (this.txt_Pwd.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请输入密码！");
                    this.txt_Pwd.Focus();
                    return;
                }
            }

            SysAdmins objAdmin = new SysAdmins()
            {
                LoginName = this.txt_LoginName.Text.Trim(),
                LoginPwd = this.txt_Pwd.Text.Trim()
            };

            if (AdminLogin(objAdmin) == null)
            {
                MessageBox.Show("用户名或密码错误！");
                this.txt_LoginName.Text = "";
                this.txt_Pwd.Text = "";
                this.txt_LoginName.Focus();
                return;
            }
            else
            {
                //登录成功，保存登录信息
                this.DialogResult = DialogResult.OK;
                CommonMethods.objAdmins = objAdmin;
            }

        }

        private SysAdmins AdminLogin(SysAdmins objAdmin)
        {
            string strSql = "Select Id,Role from sysAdmins where LoginName='{0}' and LoginPwd='{1}'";
            strSql = string.Format(strSql, objAdmin.LoginName, objAdmin.LoginPwd);
            DataSet ds = SqlHelper.GetDataSet(strSql);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];

                objAdmin.Id = Convert.ToInt32(dr["Id"]);
                objAdmin.Role = Convert.ToInt32(dr["Role"]);
                 
                return objAdmin;
            }
            else
            {
                return null;
            }
            
        }

        private void txt_LoginName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txt_Pwd.Focus();
            }
        }

        private void txt_Pwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btn_Login_Click(sender, e);
            }
        }
    }
}
